import { unionBy } from 'lodash-es'
import type { Ref } from 'vue'

import { useSelectRemote } from './useSelectRemote'

type Options = {
  domRef: Ref<any>
  defaultState?: Record<string, any>
}

export function useSearch<T extends (...args: any[]) => Promise<any>>(
  key: string,
  fn: T,
  options: Options
) {
  const { domRef, defaultState } = options

  const { remoteMethod, loading, opts } = useSelectRemote(fn, {
    valueKey: key,
    labelKey: key,
    queryKey: key,
    defaultState
  })

  const fetchFn = (query: string, cb) => {
    if (!query) {
      cb([])
      domRef.value?.close()
      return
    }
    remoteMethod(query).then(() => {
      const res = opts.value.filter(item => item.value)
      cb(unionBy(res, 'value'))
    })
  }

  return { fetchFn, remoteMethod, opts, loading }
}
